package org.example.xmut.qa.adapter.in.web.controller;


import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.xmut.qa.adapter.in.web.dto.*;
import org.example.xmut.qa.service.application.command.CreateQaCommand;
import org.example.xmut.qa.service.application.command.UpdateQaCommand;
import org.example.xmut.qa.service.application.port.in.*;
import org.example.xmut.qa.service.domain.Qa;
import org.example.xmut.qa.service.domain.valueobject.Answer;
import org.example.xmut.qa.service.domain.valueobject.QaId;
import org.example.xmut.qa.service.domain.valueobject.Question;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/qas")
@RestController
@RequiredArgsConstructor
public class qaController {

    private final GetQaListUseCase getQaListUseCase;
    private final CreateQaUseCase createQaUseCase;
    private final DeleteQaUseCase deleteQaUseCase;
    private final UpdateQaUseCase updateQaUseCase;
    private final GetQaByIdUseCase getQaByIdUseCase;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @GetMapping("")
    public List<Qa> getQas() {
        log.info("getQas");
        return getQaListUseCase.getQas();
    }

    @PostMapping()
    public Qa createQa(@RequestBody CreateQaRequestDTO createqaRequestDTO){

        CreateQaCommand command=CreateQaCommand.builder()
                .question(createqaRequestDTO.question())
                .answer(createqaRequestDTO.answer())
                .build();

        return createQaUseCase.createQa(command);
    }


    @DeleteMapping("{id}")
    public String deleteQa(@PathVariable("id") Long id){
        deleteQaUseCase.deleteQa(id);
        return "success";
    }

    @PutMapping("")
    public Qa updateQa(@RequestBody UpdateQaRequestDTO updateQaRequestDTO){
        UpdateQaCommand command=UpdateQaCommand.builder()
                .id(updateQaRequestDTO.id())
                .question(updateQaRequestDTO.question())
                .answer(updateQaRequestDTO.answer())
                .build();
        Qa qa = updateQaUseCase.updateQa(command);
        return qa;
    }


    @GetMapping("{id}")
    public QaResponseDTO getqaById(@PathVariable("id") Long id){
        Qa qa = getQaByIdUseCase.getQaById(id);
        QaResponseDTO qaResponseDTO = new QaResponseDTO(
                qa.getId().id(),
                qa.getQuestion().question(),
                qa.getAnswer().answer());
        return qaResponseDTO;
    }


//    //新增mq添加到数据库的方法
//    @GetMapping("sendObject")
//    public String sendObject() {
//        //把消息交给mq处理
//        Qa qa = new Qa();
//        qa.setId(new QaId(1L));
//        qa.setQuestion(new Question("question"));
//        qa.setAnswer(new Answer("answer"));
//        rabbitTemplate.convertAndSend("qaTest",qa);
//        return "success";
//    }

}
